<?php
include_once( "common.php" );
checkLogin( STATUS_USER );

# Check values
if ( trim( $_POST["description"] ) == "" or ! getNameByID( "Project", $_POST["project"] ) or ! getNameByID( "User", $_POST["assigned"] ) or ! getNameByID( "Priority", $_POST["priority"] ) or ! getNameByID( "Status", $_POST["status"] ) )
    outputAlert( "Invalid input", "You entered invalid input." );

# Make sure the user has visibility for this project
if ( ! canSeeProject( $_POST["project"] ) )
    outputAlert( "Insufficient privileges", "You do not have sufficient privileges to perform this action." );

# Make sure the assigned user has visibility for this project and has the proper status
$result = db_query( "SELECT * FROM UserProject WHERE UserProject.user = {$_POST["assigned"]} AND UserProject.project = {$_POST["project"]}" );
if ( $_POST["assigned"] != 0 and db_num_rows( $result ) != 1 )
    outputAlert( "Invalid user", "The assigned user does not have visibility for this project." );
if ( $_POST["assigned"] != 0 and ! hasStatus( STATUS_USER, $_POST["assigned"] ) )
    outputAlert( "Invalid user", "The assigned user does not have sufficient privileges to be assigned to this project." );

# Add the bug
$_POST["description"] = str_replace( "\r", "", $_POST["description"] );
$_POST["description"] = str_replace( "\n", "", $_POST["description"] );
$_POST["description"] = addslashes( trim( $_POST["description"] ) );
db_query( "INSERT INTO Bug VALUES( null, {$_POST["project"]}, {$_POST["assigned"]}, {$_POST["priority"]}, {$_POST["status"]}, '{$_POST["description"]}' )" ) or outputAlert( "Database error", "A database error occurred and the bug was not added." );

# Log it
$result = db_query( "SELECT LAST_INSERT_ID() AS last" );
$row = db_fetch_object( $result );
addLog( $row->last, "", null, $_SESSION["user"], 1 ) or outputAlert( "Database error", "A database error occurred and the bug was not properly logged." );

header( "Location: main.php" );
?>
